using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.UI;

namespace Rioshu.Web.ViewStateHandlers
{
    public class SqlPersister : IViewStateHandlersPersister
    {
        public void SaveState(Page page, Pair pageState)
        {
            var configuration = SqlPersisterConfigurationHandler.GetConfiguration();
            var serializer = new BinaryFormatter();
            using (var mstream = new MemoryStream()) {
                serializer.Serialize(mstream, pageState);
                var id = SqlViewstateManager.SaveState(mstream.ToArray());
                page.ClientScript.RegisterHiddenField(configuration.FieldName, id.ToString());
            }
        }

        public Pair LoadState(Page page)
        {
            var configuration = SqlPersisterConfigurationHandler.GetConfiguration();
            var stateId = page.Request.Form[configuration.FieldName];
            
            if (string.IsNullOrEmpty(stateId)) {
                return new Pair();
            }

            var id = new Guid(page.Request.Form[configuration.FieldName]);
            var viewState = SqlViewstateManager.LoadState(id);
            using (var mstream = new MemoryStream(viewState)) {
                var serializer = new BinaryFormatter();
                return (Pair) serializer.Deserialize(mstream);
            }
        }
    }
}